package com.xxhui.piedemo.View;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.xxhui.piedemo.bean.PieData;

import java.util.ArrayList;
import java.util.List;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * Created by hui on 2016/6/16.
 */
public class PieChart extends View {

    private static final String TAG = "PieChart";
    // 颜色表
    private int[] mColors = {Color.BLUE, Color.CYAN, Color.DKGRAY, Color.GRAY, Color.GREEN,
            Color.LTGRAY, Color.WHITE, Color.RED, Color.YELLOW};

    // 饼状图初始绘制角度
    private float mStartAngle = 0;

    // 数据
    private List<PieData> mData;

    // 宽高
    private int cur_width, cur_height;

    private int wish_width , wish_height;

    // 画笔
    private Paint mPaint = new Paint();

    private int down_x;

    private int down_y;

    private int move_to_lest_local_x;

    private int move_to_lest_local_y;

    private int autoDataCount = 6;

    public PieChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PieChart(Context context) {
        super(context);
    }

    //当宽高改变的时候记录下改变后的宽高
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        cur_height = h;
        cur_width = w;
        wish_width = Math.max(w ,oldw);
        wish_height = Math.max(h , oldh);
        Log.i(TAG, "onSizeChanged: "+cur_width+"  "+cur_height+"  "+wish_width+"  "+wish_height);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
        Log.i(TAG, "onMeasure: "+measureWidth(widthMeasureSpec));
    }

    private int measureWidth(int widthMeasureSpec){
        int result = 0 ;
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);

        switch (mode){
            case MeasureSpec.EXACTLY://固定大小或者match_parent、fill_parent
                result = size;
                break;
            case MeasureSpec.AT_MOST://wrap_content
                wish_width = getDefaultSize(size,widthMeasureSpec);
                result = Math.max(size,wish_height)/2;
                if(result==0)
                    result = 200;
                break;
            case MeasureSpec.UNSPECIFIED://未指明的
                break;
            default:
                break;
        }
        return result;
    }

    private int measureHeight(int heightMeasureSpec){
        int result = 0 ;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);

        switch (mode){
            case MeasureSpec.EXACTLY://固定大小或者match_parent、fill_parent
                result = size;
                break;
            case MeasureSpec.AT_MOST://wrap_content
                wish_height = getDefaultSize(size,heightMeasureSpec);
                result = Math.min(size,wish_height)/2;
                if(result==0)
                    result = 200;
                break;
            case MeasureSpec.UNSPECIFIED://未指明的
                break;
            default:
                break;
        }
        return result;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (null == mData)
            return;
        canvas.drawARGB(98, 98, 98, 98);
        float currentStartAngle = mStartAngle;                    // 当前起始角度
        canvas.translate(cur_width / 2, cur_height / 2);                // 将画布坐标原点移动到中心位置
        float r = (float) (Math.min(cur_height, cur_width) / 2 * 0.8);  // 饼状图半径
        RectF rect = new RectF(-r, -r, r, r);                     // 饼状图绘制区域

        for (int i = 0; i < mData.size(); i++) {
            PieData pie = mData.get(i);
            mPaint.setColor(pie.getColor());
            canvas.drawArc(rect, currentStartAngle, pie.getAngle(), true, mPaint);
            currentStartAngle += pie.getAngle();
        }
        Log.i(TAG, "onDraw: ");
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                down_x = (int) event.getRawX();
                down_y = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                move_to_lest_local_x = (int) event.getRawX();
                move_to_lest_local_y = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_UP:
                if (down_x - move_to_lest_local_x > 0) {
                    setData(getAutoData(autoDataCount--));
                } else {
                    setData(getAutoData(autoDataCount++));
                }
                if (autoDataCount <= 0 ) {
                    Toast.makeText(getContext(), "大哥你想干嘛,饼图都要没了(＞﹏＜)", LENGTH_SHORT).show();
                    autoDataCount = 0;
                    break;
                }
                //Toast.makeText(getContext(), String.valueOf(autoDataCount), Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        Log.i(TAG, "onTouchEvent: ");
        return true;
    }

    // 初始化数据（根据Arraylist的数据完成其余数据的填充，作为辅助方法，声明为private）
    private void initDate(List<PieData> mData) {
        if (null == mData || mData.size() == 0)   // 数据有问题 直接返回
            return;

        float sumValue = 0;
        for (int i = 0; i < mData.size(); i++) {
            PieData pie = mData.get(i);

            sumValue += pie.getValue();       //计算数值和

            int j = i % mColors.length;       //设置颜色，循环颜色分配
            pie.setColor(mColors[j]);
        }

        float sumAngle = 0;
        for (int i = 0; i < mData.size(); i++) {
            PieData pie = mData.get(i);

            float percentage = pie.getValue() / sumValue;   // 百分比
            float angle = percentage * 360;                 // 对应的角度

            pie.setPercentage(percentage);                  // 记录百分比
            pie.setAngle(angle);                            // 记录角度大小
            sumAngle += angle;
            Log.i("angle", "" + pie.getAngle());
        }
        Log.i("sumAngle", "" + sumAngle);
    }

    // 设置数据
    public void setData(List<PieData> mData) {
        this.mData = mData;
        initDate(mData);
        invalidate();   // 刷新
    }

    // 设置起始角度
    public void setStartAngle(int mStartAngle) {
        this.mStartAngle = mStartAngle;
        invalidate();   // 刷新
    }

    private List<PieData> getAutoData(int num) {

        List<PieData> list = new ArrayList<PieData>();
        for (int i = 0; i < num; i++) {
            PieData data = new PieData();
            data.setName(String.valueOf(i));
            data.setValue((float) Math.random() * 100.0f);
            list.add(data);
        }
        return list;
    }


}

